package com.example.receiptocr.ocr

import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import java.math.BigDecimal
import androidx.compose.ui.graphics.Color
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.receiptocr.viewModels.OCRResultViewModel
import com.example.receiptocr.viewModels.OCRResultState

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OCRResultScreen(
    receiptId: Long, // 可选参数，如果为null则表示新建票据
    viewModel: OCRResultViewModel = hiltViewModel(),
    uri: Uri,
    onNavigateBack: () -> Unit = {},
    onSaveAndReturn: () -> Unit = {}
) {
    val resultState by viewModel.resultState.collectAsState()

    LaunchedEffect(Unit) {
        viewModel.ocrReceipt(uri)
    }

    when (val state = resultState) {
        is OCRResultState.Loading -> {
            // 加载中的进度条
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }
        is OCRResultState.Success -> {
            val result = state.backReceipt
            var resultRemember by remember { mutableStateOf(result) }
            var resultListRemember by remember { mutableStateOf(result.receiptDataList)}
            Box(modifier = Modifier.fillMaxSize()) {
                Scaffold(
                    topBar = {
                        TopAppBar(
                            title = { Text("新建票据") },
                            navigationIcon = {
                                IconButton(onClick = onNavigateBack) {
                                    Icon(Icons.Default.ArrowBack, "返回")
                                }
                            }
                        )
                    }
                ) { paddingValues ->
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(paddingValues)
                            .padding(16.dp)
                            .padding(bottom = 80.dp),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        // 基本信息部分
                        item {
                            Text(
                                text = "票据基本信息",
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )

                            EditableInfoItem(
                                label = "票据名称",
                                value = result.receiptName,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(receiptName = newValue)
                                }
                            )

                            EditableInfoItem(
                                label = "票据代码",
                                value = result.receiptCode.toString(),
                                onValueChange = { newValue ->
                                    try {
                                        resultRemember = result.copy(receiptCode = newValue.toLong())
                                    } catch (e: Exception) {
                                        // 处理转换错误
                                    }
                                }
                            )

                            EditableInfoItem(
                                label = "票据号码",
                                value = result.receiptNumber.toString(),
                                onValueChange = { newValue ->
                                    try {
                                        resultRemember = result.copy(receiptNumber = newValue.toLong())
                                    } catch (e: Exception) {
                                        // 处理转换错误
                                    }
                                }
                            )

                            EditableInfoItem(
                                label = "票据时间",
                                value = result.receiptDate.toString(),
                                onValueChange = { newValue ->
                                    // 这里可以添加日期选择器的逻辑
                                    // 暂时保持原值
                                }
                            )
                        }

                        // 购买方信息
                        item {
                            Text(
                                text = "购买方信息",
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.padding(vertical = 8.dp)
                            )

                            EditableInfoItem(
                                label = "名称",
                                value = result.purchaserName,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(purchaserName = newValue)
                                }
                            )
                            EditableInfoItem(
                                label = "纳税人识别号",
                                value = result.purchaserCode,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(purchaserCode = newValue)
                                }
                            )
                            EditableInfoItem(
                                label = "地址和电话",
                                value = result.purchaserAddress,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(purchaserAddress = newValue)
                                }
                            )
                            EditableInfoItem(
                                label = "开户行及账号",
                                value = result.purchaserBank,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(purchaserBank = newValue)
                                }
                            )
                        }

                        // 销售方信息
                        item {
                            Text(
                                text = "销售方信息",
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.padding(vertical = 8.dp)
                            )

                            EditableInfoItem(
                                label = "名称",
                                value = result.sellerName,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(sellerName = newValue)
                                }
                            )
                            EditableInfoItem(
                                label = "纳税人识别号",
                                value = result.sellerCode,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(sellerCode = newValue)
                                }
                            )
                            EditableInfoItem(
                                label = "地址和电话",
                                value = result.sellerAddress,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(sellerAddress = newValue)
                                }
                            )
                            EditableInfoItem(
                                label = "开户行及账号",
                                value = result.sellerBank,
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(sellerBank = newValue)
                                }
                            )
                        }

                        // 项目信息
                        item {
                            Text(
                                text = "项目明细",
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.padding(vertical = 8.dp)
                            )
                        }

                        // 项目卡片列表
                        items(resultListRemember) { projectData ->
                            EditableProjectCard(
                                projectData = projectData,
                                onProjectDataChange = { newProjectData ->
                                    val index = result.receiptDataList.indexOf(projectData)
                                    resultListRemember = result.receiptDataList.toMutableList().apply {
                                        set(index, newProjectData)
                                    }
                                }
                            )
                        }

                        // 总计信息
                        item {
                            Divider(modifier = Modifier.padding(vertical = 8.dp))
                            EditableInfoItem(
                                label = "总金额",
                                value = result.totalAmount.toString(),
                                onValueChange = { newValue ->
                                    try {
                                        resultRemember = result.copy(totalAmount = newValue.toDouble())
                                    } catch (e: Exception) {
                                        // 处理转换错误
                                    }
                                }
                            )
                            EditableInfoItem(
                                label = "备注",
                                value = result.note ?: "",
                                onValueChange = { newValue ->
                                    resultRemember = result.copy(note = newValue)
                                }
                            )
                        }
                    }
                }

                // 保存按钮
                Button(
                    onClick = {
                        viewModel.saveReceipt(result)
                        onSaveAndReturn()
                    },
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(16.dp)
                        .height(48.dp)
                ) {
                    Text("确认保存")
                }
            }
        }

        is OCRResultState.Error -> {

        }
    }



}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditableInfoItem(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.weight(1f)
        )
        TextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .weight(2f)
                .padding(start = 16.dp),
            textStyle = MaterialTheme.typography.bodyLarge,
            colors = TextFieldDefaults.colors(
                focusedContainerColor = Color.Transparent,
                unfocusedContainerColor = Color.Transparent,
                disabledContainerColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                cursorColor = MaterialTheme.colorScheme.primary
            ),
            singleLine = true
        )
    }
}

@Composable
fun EditableProjectCard(
    projectData: ReceiptData,
    onProjectDataChange: (ReceiptData) -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            EditableInfoItem(
                label = "项目名称",
                value = projectData.projectName.toString(),
                onValueChange = { newValue ->
                    onProjectDataChange(projectData.copy(projectName = newValue))
                }
            )
            EditableInfoItem(
                label = "规格",
                value = projectData.projectSpecs.toString(),
                onValueChange = { newValue ->
                    onProjectDataChange(projectData.copy(projectSpecs = newValue))
                }
            )
            EditableInfoItem(
                label = "单价",
                value = projectData.unitPrice.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(unitPrice = newValue.toDouble()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "数量",
                value = projectData.quantity.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(quantity = newValue.toLong()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "金额",
                value = projectData.amount.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(amount = newValue.toDouble()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "税率",
                value = projectData.taxRate.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(taxRate = newValue.toLong()))
                    } catch (e: Exception) {}
                }
            )
            EditableInfoItem(
                label = "税款",
                value = projectData.taxPayment.toString(),
                onValueChange = { newValue ->
                    try {
                        onProjectDataChange(projectData.copy(taxPayment = newValue.toDouble()))
                    } catch (e: Exception) {}
                }
            )
        }
    }
}

data class ReceiptData(
    val dataId: Long,
    val receiptId: Long,
    val projectName: String? = null,
    val projectSpecs: String? = null,
    val unitPrice: Double = 0.0,
    val quantity: Long,
    val amount: Double = 0.0,
    val taxRate: Long,
    val taxPayment: Double = 0.0
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readLong(),
        parcel.readLong(),
        parcel.readString(),
        parcel.readString(),
        parcel.readDouble(),
        parcel.readLong(),
        parcel.readDouble(),
        parcel.readLong(),
        parcel.readDouble()
    ) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeLong(dataId)
        parcel.writeLong(receiptId)
        parcel.writeString(projectName)
        parcel.writeString(projectSpecs)
        parcel.writeDouble(unitPrice)
        parcel.writeLong(quantity)
        parcel.writeDouble(amount)
        parcel.writeLong(taxRate)
        parcel.writeDouble(taxPayment)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<ReceiptData> {
        override fun createFromParcel(parcel: Parcel): ReceiptData {
            return ReceiptData(parcel)
        }

        override fun newArray(size: Int): Array<ReceiptData?> {
            return arrayOfNulls(size)
        }
    }
}

